package com.ziyucoding.springboot.labs.lab10.seatdemo.atscfeign.productservice.controller;

import com.ziyucoding.springboot.labs.lab10.seatdemo.atscfeign.productservice.dto.ProductReduceStockDTO;
import com.ziyucoding.springboot.labs.lab10.seatdemo.atscfeign.productservice.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 商品 控制器
 *
 * @author ziyucoding
 * @date 2022-11-03
 **/
@RestController
@RequestMapping("/product")
public class ProductController {

    private Logger logger = LoggerFactory.getLogger(ProductController.class);

    @Autowired
    private ProductService productService;

    @PostMapping("/reduce-stock")
    public Map<String, Object> createOrder(@RequestBody ProductReduceStockDTO productReduceStockDTO) {
        logger.info("[reduceStock] 收到减少库存请求, 商品:{}, 价格:{}", productReduceStockDTO.getProductId(),
                productReduceStockDTO.getAmount());
        boolean isSuccess = false;
        try {
            productService.reduceStock(productReduceStockDTO.getProductId(), productReduceStockDTO.getAmount());
            // 正常扣除库存，返回 true
            isSuccess = true;
        } catch (Exception e) {
            // 失败扣除库存，返回 false
            logger.error("扣除库存失败", e);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("msg", "成功");
        result.put("data", isSuccess);
        return result;
    }

}
